package com.xw.controller;

import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.common.TokenHandler;
import com.xw.dao.ThumbsDao;
import com.xw.entity.Thumbs;
import com.xw.entity.User;
import com.xw.rep.QueryNumberRep;
import com.xw.req.PageRequest;
import com.xw.service.RedisService;
import com.xw.service.ThumbsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 点赞/收藏模块(Thumbs)模块
 */
@RestController
@RequestMapping("thumbs")
@Api(tags = "点赞/收藏模块(Thumbs)模块")
public class ThumbsController {
    /**
     * 服务对象
     */
    @Resource
    private ThumbsService thumbsService;

    @Resource
    private ThumbsDao thumbsDao;

    @Resource
    private RedisService redisService;
    // 注入RedisService

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result<?> findPage(@RequestBody PageRequest<Thumbs> pageRequest) {
        return new Result<>(this.thumbsService.queryByPage(pageRequest), Constants.SUCCESS);
    }

    /**
     * 获取高赞帖子
     * @return 高赞帖子列表
     */
    @GetMapping("/highRankPosts")
    @ApiOperation(value = "获取高赞帖子")
    public Result<?> getHighRankPosts() {
        // 获取点赞数最多的帖子
        List<Map<String, Object>> highRankPosts = thumbsService.getHighRankPosts();
        return new Result<>(highRankPosts, Constants.SUCCESS);
    }

    /**
     * 点赞/收藏
     *
     * @param thumbs 实体
     * @return 新增/修改结果
     */
    @PostMapping
    @ApiOperation(value = "点赞/收藏")
    public Result<?> saveOrUpdate(@RequestBody @Validated Thumbs thumbs) {
        User userInfo = TokenHandler.getUserInfo();
        thumbs.setUserId(userInfo.getId());
        Integer linkId = thumbs.getLinkId(); // 直接使用Integer类型
        Integer userId = userInfo.getId(); // 直接使用Integer类型

        // 根据类型判断是点赞还是收藏
        boolean isLiked = redisService.isLiked(String.valueOf(linkId), String.valueOf(userId));
        boolean isCollected = redisService.isCollected(String.valueOf(linkId), String.valueOf(userId));

        boolean likeResult = false;
        boolean collectResult = false;

        if (thumbs.getType() == 0 && !isLiked) {
            // 点赞操作
            likeResult = redisService.like(String.valueOf(linkId), String.valueOf(userId));
        } else if (thumbs.getType() == 0 && isLiked) {
            // 取消点赞操作
            likeResult = redisService.unlike(String.valueOf(linkId), String.valueOf(userId));
        }

        if (thumbs.getType() == 2 && !isCollected) {
            // 收藏操作
            collectResult = redisService.collect(String.valueOf(linkId), String.valueOf(userId));
        } else if (thumbs.getType() == 2 && isCollected) {
            // 取消收藏操作
            collectResult = redisService.uncollect(String.valueOf(linkId), String.valueOf(userId));
        }

        if (likeResult) {
            this.thumbsDao.insert(thumbs);
        }
        if (collectResult) {
            this.thumbsDao.insert(thumbs);
        }

        // 根据操作结果返回成功或失败
        return new Result<>(Constants.SUCCESS);
    }

    /**
     * 删除数据
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据(ID)")
    public Result<?> delete(@PathVariable("id") Integer id) {
        this.thumbsDao.deleteById(id);
        return new Result<>(Constants.SUCCESS);
    }

    @PostMapping("/deleteByIds")
    @ApiOperation(value = "批量删除")
    public Result<?> deleteByIds(@RequestBody List<Integer> ids) {
        this.thumbsDao.deleteBatchByIds(ids);
        return new Result<>(Constants.SUCCESS);
    }

    /**
     * 取消点赞或收藏
     *
     * @param linkId 链接ID
     * @param type 类型
     * @return 取消是否成功
     */
    @GetMapping("/deleteByLinkIdAndUserId")
    @ApiOperation(value = "取消点赞或收藏")
    public Result<?> deleteByLinkIdAndUserId(@RequestParam Integer linkId, @RequestParam Integer type) {
        User userInfo = TokenHandler.getUserInfo();
        Integer userId = userInfo.getId(); // 直接使用Integer类型

        // 调用RedisService来取消点赞或收藏
        boolean isUnliked = false;
        boolean isUncollected = false;

        if (type == 0) { // 0 代表点赞
            isUnliked = redisService.unlike(String.valueOf(linkId), String.valueOf(userId));
        } else if (type == 2) { // 2 代表收藏
            isUncollected = redisService.uncollect(String.valueOf(linkId), String.valueOf(userId));
        }

        if (isUnliked) {
            // 如果Redis取消点赞成功，则删除数据库中的点赞记录
            this.thumbsDao.deleteByLinkIdAndUserId(linkId, userId, type);
        } else if (isUncollected) {
            this.thumbsDao.deleteByLinkIdAndUserId(linkId, userId, type);
        }

        return new Result<>(Constants.SUCCESS);
    }

    /**
     * 查询数量
     *
     * @param linkId 链接ID
     * @return 查询结果
     */
    @GetMapping("/queryNumber")
    @ApiOperation(value = "查询数量")
    public Result<?> queryNumber(@RequestParam Integer linkId) {
        List<QueryNumberRep> map = thumbsService.queryNumber(linkId);
        return new Result<>(map,Constants.SUCCESS);
    }
}

